package com.xhwl.logistics.validate.time;

import org.apache.commons.lang3.ObjectUtils;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Method;
import java.util.Date;

public class ValidTimeRangeConstraintValidator implements ConstraintValidator<ValidTimeRangeConstraint, Object> {

    private static final String methodNameForEnterStartTime = "getEnterStartTime";
    private static final String methodNameForEnterEndTime = "getEnterEndTime";

    @Override
    public boolean isValid(Object object, ConstraintValidatorContext context) {
        Class<?> clazz = object.getClass();

        Method methodForGetEnterStartTime = ReflectionUtils.findMethod(clazz, methodNameForEnterStartTime);
        Method methodForGetEnterEndTime = ReflectionUtils.findMethod(clazz, methodNameForEnterEndTime);
        Assert.notNull(methodForGetEnterStartTime, "验证的对象不具有时间区间的开始时间，因此不能使用时间区间验证");
        Assert.notNull(methodForGetEnterEndTime, "验证的对象不具有时间区间的结束时间，因此不能使用时间区间验证");

        Object objectForEnterStartTime = ReflectionUtils.invokeMethod(methodForGetEnterStartTime, object);
        Object objectForEnterEndTime = ReflectionUtils.invokeMethod(methodForGetEnterEndTime, object);

        if (ObjectUtils.allNull(objectForEnterStartTime, objectForEnterEndTime)) {
            return true;
        } else if (ObjectUtils.allNotNull(objectForEnterStartTime, objectForEnterEndTime)) {
            Assert.isInstanceOf(Date.class, objectForEnterStartTime, "时间区间的开始时间必须是Date类型");
            Assert.isInstanceOf(Date.class, objectForEnterEndTime, "时间区间的结束时间必须是Date类型");
            return true;
        } else {
            return false;
        }
    }

}
